<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .w {
            width: 1200px;
            margin: 10px auto;
        }

        .header {
            height: 100px;
            background-color: purple;
        }

        .banner {
            height: 200px;
            background-color: rgb(129, 129, 201);
        }

        .nav {
            height: 1000px;
            background-color: rgb(88, 216, 88);
        }

        .footer {
            height: 300px;
            background-color: #ff6700;
        }

        .slider-bar {
            position: absolute;
            left: 50%;
            top: 200px;
            margin-left: 600px;
            width: 45px;
            height: 130px;
            background-color: pink;
        }

        .slider-bar span {
            position: absolute;
            display: none;
            bottom: 0;
            text-align: center;
        }
    </style>
</head>

<body>
    <div class="slider-bar">
        <span class="goBack">返回顶部</span>
    </div>
    <div class="header w">头部</div>
    <div class="banner w">内容</div>
    <div class="nav w">主体</div>
    <div class="footer w ">尾部</div>
    <script>
        var sliderbar = document.querySelector('.slider-bar');
        var goBack = document.querySelector('.goBack');
        var banner = document.querySelector('.banner');
        //nav.offsetTop 被卷去头部的大小
        var bannerTop = banner.offsetTop;

        //当我们侧边栏固定定位之后变化的数值
        var sliderbarTop = sliderbar.offsetTop - bannerTop;


            window.addEventListener('scroll', function () {
                //被卷去的头部
                //console.log(window.pageYOffset);

                //当卷去头部大于了  500就把侧边栏改为固定定位
                if (window.pageYOffset >= bannerTop) {
                    sliderbar.style.position = 'fixed';
                    sliderbar.style.top = sliderbarTop + 'px';
                    goBack.style.display = 'block';
                    
                } else {
                    sliderbar.style.position = 'absolute';
                    sliderbar.style.top = 200 + 'px';
                    goBack.style.display = 'none';
                }
            })
    </script>
</body>

</html>